package com.gitee.ywj1352.kafka;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

/**
 * @author wenjie.yang on 2019/6/20.
 */
public class KafkaProducerDemo extends Thread {

    private final KafkaProducer<Integer,String> producer;

    private final boolean isAsync;


    private final String topic;

    public KafkaProducerDemo(String topic,boolean isAsync) {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"127.0.0.1:9092");
        properties.put(ProducerConfig.CLIENT_ID_CONFIG,"KafkaProducerDemo");
        //所以得follower 都HW都设置成功 才 能消费
        properties.put(ProducerConfig.ACKS_CONFIG,"-1");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.IntegerSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        //配置分区算法
        properties.put(ProducerConfig.PARTITIONER_CLASS_CONFIG,"com.gitee.ywj1352.kafka.MyPartition");
        this.producer = new KafkaProducer(properties);
        this.topic = topic;
        this.isAsync = isAsync;
    }

    @Override
    public void run() {
        int i= 0;
        while (i < 50) {
            String message = "msg" + i;
            System.out.println("begin send message: " + message);
            if (isAsync){
                //异步发送 在kafka 1.0 之后就是异步发送
                producer.send(new ProducerRecord<>(topic,i,message), new Callback() {
                    @Override
                    public void onCompletion(RecordMetadata metadata, Exception exception) {
                        if (metadata != null){
                            System.out.println("async-offset :" + metadata.offset() +"-> " +metadata.partition());
                        }
                    }
                });
            }else{
                //同步发送 future/callback
                try {
                    RecordMetadata recordMetadata = producer.send(new ProducerRecord<Integer, String>(topic, message)).get();//get是future 的阻塞方法
                    System.out.println("sync-offset :" + recordMetadata.offset() +"-> " +recordMetadata.partition());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
            i++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        KafkaProducerDemo test = new KafkaProducerDemo("ywj",true);
        test.start();
    }

}
